// pages/product-detail/product-detail.js
const { get, post } = require("../../utils/request.js");
const { addToCart } = require("../../api/cart.js");
const { createOrder } = require("../../api/order.js");
const {
  navigateFromProductDetailToCart,
} = require("../../utils/navigation-history.js");

Page({
  data: {
    productId: "",
    productDetail: {},
    selectedSku: {},
    loading: false,
    currentImageIndex: 0,
    relatedProducts: [],
    fromCart: false,
    cartId: "",
    cartSpecInfo: null,
  },

  onLoad(options) {
    const { productId, fromCart, cartId } = options;
    if (productId) {
      this.setData({
        productId,
        fromCart: fromCart === "true",
        cartId: cartId || "",
      });
      // 保存商品ID到全局数据，用于购物车返回
      getApp().globalData.lastProductId = productId;
      this.loadProductDetail();
    } else {
      wx.showToast({
        title: "商品ID不存在",
        icon: "none",
      });
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
    }
  },

  onShow() {
    // 更新TabBar状态
    const app = getApp();
    app.updateCustomTabBar();
  },

  // 加载商品详情
  async loadProductDetail() {
    try {
      this.setData({ loading: true });

      const res = await get(`/client/product/detail/${this.data.productId}`);

      if (res && res.code === 0 && res.data) {
        const productDetail = res.data;

        // 解析SKU规格文本
        if (productDetail.productSkus && productDetail.productSkus.length > 0) {
          productDetail.productSkus.forEach((sku) => {
            sku.specsText = this.parseSpecText(sku.specs);
            // 统一处理规格图片字段
            sku.specImageUrl = this.getSpecImageUrl(sku);
          });
        }

        // 设置默认选中的SKU
        const selectedSku = productDetail.productSkus[0] || {};

        this.setData({
          productDetail: productDetail,
          selectedSku: selectedSku,
        });

        console.log("商品详情加载成功:", productDetail);

        // 如果是从购物车跳转，应用规格信息
        if (this.data.fromCart) {
          this.applyCartSpecInfo();
        }

        // 加载更多商品
        this.loadMoreProducts();
      } else {
        console.error("获取商品详情失败:", res);
        wx.showToast({
          title: res.message || "获取商品详情失败",
          icon: "none",
        });
      }
    } catch (error) {
      console.error("加载商品详情失败:", error);
      wx.showToast({
        title: "网络错误，请重试",
        icon: "none",
      });
    } finally {
      this.setData({ loading: false });
    }
  },

  // 应用购物车规格信息
  applyCartSpecInfo() {
    const app = getApp();
    const cartSpecInfo = app.globalData.cartToProductSpec;

    if (cartSpecInfo && cartSpecInfo.skuId) {
      console.log("应用购物车规格信息:", cartSpecInfo);

      // 查找对应的SKU - 使用skuId匹配productSkus中的id
      const targetSku = this.data.productDetail.productSkus.find(
        (sku) => sku.id === cartSpecInfo.skuId
      );

      if (targetSku) {
        console.log("找到匹配的SKU:", targetSku);
        this.setData({
          selectedSku: targetSku,
          cartSpecInfo: cartSpecInfo,
        });

        // 显示提示信息
        wx.showToast({
          title: "已定位到购物车规格",
          icon: "success",
          duration: 1500,
        });
      } else {
        console.log("未找到匹配的SKU，使用默认规格");
      }
    }
  },

  // 选择SKU
  selectSku(e) {
    const sku = e.currentTarget.dataset.sku;
    this.setData({
      selectedSku: sku,
    });

    console.log("选择SKU:", sku);
  },

  // 解析SKU规格显示文本
  // 获取规格图片URL
  getSpecImageUrl(sku) {
    // 尝试多个可能的字段名
    const possibleFields = [
      "specImage",
      "image",
      "skuImage",
      "specImg",
      "skuImg",
      "specificationImage",
      "variantImage",
    ];

    for (const field of possibleFields) {
      if (sku[field] && typeof sku[field] === "string" && sku[field].trim()) {
        // console.log(`找到规格图片字段: ${field} = ${sku[field]}`);
        return sku[field];
      }
    }

    console.log("未找到规格图片字段，SKU字段:", Object.keys(sku));
    return "";
  },

  parseSpecText(specs) {
    try {
      const specObj = JSON.parse(specs);
      const specArray = [];

      for (const key in specObj) {
        if (Array.isArray(specObj[key])) {
          specArray.push(`${key}: ${specObj[key].join(", ")}`);
        } else {
          specArray.push(`${key}: ${specObj[key]}`);
        }
      }

      return specArray.join(" | ");
    } catch (error) {
      console.error("解析规格失败:", error);
      return specs;
    }
  },

  // 返回上一页

  // 轮播图变化事件
  onSwiperChange(e) {
    this.setData({
      currentImageIndex: e.detail.current,
    });
  },

  // 调用更多商品接口
  async loadMoreProducts() {
    try {
      const { productDetail } = this.data;
      if (!productDetail.categoryId) {
        console.log("没有分类ID，跳过加载更多商品");
        return;
      }

      const response = await post(
        `/client/product/more/${this.data.productId}`,
        {
          categoryId: productDetail.categoryId,
        }
      );

      if (response.code === 0) {
        this.setData({
          relatedProducts: response.data || [],
        });
        console.log("加载更多商品成功:", response.data);
      } else {
        console.error("加载更多商品失败:", response.message);
      }
    } catch (error) {
      console.error("加载更多商品接口调用失败:", error);
    }
  },

  // 点击推荐商品
  onProductTap(e) {
    const product = e.currentTarget.dataset.product;
    if (product && product.id) {
      wx.navigateTo({
        url: `/pages/product-detail/product-detail?productId=${product.id}`,
      });
    }
  },

  // 添加到购物车
  async addToCart() {
    if (!this.data.selectedSku.id) {
      wx.showToast({
        title: "请选择商品规格",
        icon: "none",
      });
      return;
    }

    try {
      wx.showLoading({ title: "添加中..." });

      const params = {
        spuId: this.data.productDetail.id,
        skuId: this.data.selectedSku.id,
        quantity: 1,
      };

      const response = await addToCart(params);

      wx.hideLoading();

      if (response.code === 0) {
        // 设置全局添加购物车动作标记
        const app = getApp();
        app.globalData.addCarAction = true;

        wx.showToast({
          title: "已添加到购物车",
          icon: "success",
        });
      } else {
        wx.showToast({
          title: response.message || "添加失败",
          icon: "none",
        });
      }
    } catch (error) {
      wx.hideLoading();
      console.error("添加到购物车失败:", error);
      wx.showToast({
        title: "网络错误，请重试",
        icon: "none",
      });
    }
  },

  // 跳转到购物车页面
  goToCart() {
    console.log("商品详情页：点击购物车按钮，productId:", this.data.productId);
    // 使用新的导航历史管理
    navigateFromProductDetailToCart(this.data.productId);
  },

  // 立即购买
  async buyNow() {
    if (!this.data.selectedSku.id) {
      wx.showToast({
        title: "请选择商品规格",
        icon: "none",
      });
      return;
    }

    try {
      wx.showLoading({ title: "创建订单中..." });

      // 构建商品数据
      const items = [
        {
          spuId: this.data.productDetail.id,
          skuId: this.data.selectedSku.id,
          quantity: 1,
          unitPrice: this.data.selectedSku.price.toString(),
        },
      ];

      const orderData = {
        orderType: 1, // 普通订单
        addressId: "", // 立即购买时没有地址，让用户在订单确认页面选择
        remark: "",
        usePoints: true,
        create: false, // 预览订单
        items: items,
      };

      const response = await createOrder(orderData);

      wx.hideLoading();

      if (response.code === 0) {
        // 构建购物车商品数据，用于订单确认页面
        const checkoutItems = [
          {
            id: `temp_${Date.now()}`, // 临时ID
            spuId: this.data.productDetail.id,
            skuId: this.data.selectedSku.id,
            spuName: this.data.productDetail.spuName,
            mainImage: this.data.productDetail.mainImage,
            specValues: this.data.selectedSku.specsText || "",
            specImage: this.data.selectedSku.specImageUrl || "", // 使用统一的规格图片字段
            unitPrice: this.data.selectedSku.price,
            quantity: 1,
          },
        ];

        // 将商品数据存储到全局数据中
        getApp().globalData.checkoutItems = checkoutItems;

        // 跳转到订单确认页面
        wx.navigateTo({
          url: "/pages/order-confirm/order-confirm",
        });
      } else {
        wx.showToast({
          title: response.message || "创建订单失败",
          icon: "none",
        });
      }
    } catch (error) {
      wx.hideLoading();
      console.error("立即购买失败:", error);
      wx.showToast({
        title: "网络错误，请重试",
        icon: "none",
      });
    }
  },
});
